package com.tedu.egweibo.controller;

import com.tedu.egweibo.mapper.WeiboMapper;
import com.tedu.egweibo.pojo.dto.WeiboDTO;
import com.tedu.egweibo.pojo.entity.User;
import com.tedu.egweibo.pojo.entity.Weibo;
import com.tedu.egweibo.pojo.vo.WeiboDetailVO;
import com.tedu.egweibo.pojo.vo.WeiboVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/weibo")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    @PostMapping("/insert")
    public int insert(@RequestBody WeiboDTO weiboDTO, HttpSession session) {
        User user = new User();
        user = (User) session.getAttribute("user");
        if (user != null) {
            Weibo weibo = new Weibo();
            BeanUtils.copyProperties(weiboDTO, weibo);
            weibo.setUserId(user.getId());
            weibo.setCreated(new Date());
            weiboMapper.insert(weibo);
            return 1;
        } else {
            return 2;
        }
    }

    @GetMapping("/selectIndex")
    public List<WeiboVO> selectIndex() {
        return weiboMapper.selectAll();
    }

    @GetMapping("/selectDetail")
    public WeiboDetailVO selectDetail(Integer id) {
        return weiboMapper.selectById(id);
    }

    @GetMapping("/selectByUserId")
    public List<Weibo> selectByUserId(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Weibo> weibo = weiboMapper.selectByUserId(user.getId());
        return weibo;
    }

}
